import { ref, computed, watch } from 'vue'

export type Theme = 'light' | 'dark' | 'auto'

export function useTheme() {
  const currentTheme = ref<Theme>('auto')
  const systemTheme = ref<'light' | 'dark'>('light')

  // 检测系统主题
  const detectSystemTheme = () => {
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      systemTheme.value = 'dark'
    } else {
      systemTheme.value = 'light'
    }
  }

  // 计算实际主题
  const effectiveTheme = computed(() => {
    if (currentTheme.value === 'auto') {
      return systemTheme.value
    }
    return currentTheme.value
  })

  // 应用主题
  const applyTheme = (theme: 'light' | 'dark') => {
    const root = document.documentElement

    if (theme === 'dark') {
      root.classList.add('dark')
      root.style.setProperty('--text-primary', '#f7fafc')
      root.style.setProperty('--text-secondary', '#a0aec0')
      root.style.setProperty('--bg-primary', '#1a202c')
      root.style.setProperty('--bg-secondary', '#2d3748')
      root.style.setProperty('--border-color', '#4a5568')
    } else {
      root.classList.remove('dark')
      root.style.setProperty('--text-primary', '#2d3748')
      root.style.setProperty('--text-secondary', '#718096')
      root.style.setProperty('--bg-primary', '#ffffff')
      root.style.setProperty('--bg-secondary', '#f7fafc')
      root.style.setProperty('--border-color', '#e2e8f0')
    }
  }

  // 设置主题
  const setTheme = (theme: Theme) => {
    currentTheme.value = theme
    localStorage.setItem('theme', theme)
  }

  // 切换主题
  const toggleTheme = () => {
    const themes: Theme[] = ['light', 'dark', 'auto']
    const currentIndex = themes.indexOf(currentTheme.value)
    const nextIndex = (currentIndex + 1) % themes.length
    setTheme(themes[nextIndex])
  }

  // 初始化主题
  const initTheme = () => {
    // 从localStorage读取保存的主题
    const savedTheme = localStorage.getItem('theme') as Theme
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      currentTheme.value = savedTheme
    }

    // 检测系统主题
    detectSystemTheme()

    // 监听系统主题变化
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', detectSystemTheme)
    }

    // 应用初始主题
    applyTheme(effectiveTheme.value)
  }

  // 监听主题变化
  watch(effectiveTheme, (newTheme) => {
    applyTheme(newTheme)
  })

  // 主题图标
  const themeIcon = computed(() => {
    switch (currentTheme.value) {
      case 'light':
        return '☀️'
      case 'dark':
        return '🌙'
      case 'auto':
        return '🔄'
      default:
        return '☀️'
    }
  })

  // 主题文本
  const themeText = computed(() => {
    switch (currentTheme.value) {
      case 'light':
        return '浅色模式'
      case 'dark':
        return '深色模式'
      case 'auto':
        return '自动模式'
      default:
        return '浅色模式'
    }
  })

  return {
    currentTheme,
    effectiveTheme,
    systemTheme,
    setTheme,
    toggleTheme,
    initTheme,
    themeIcon,
    themeText
  }
}

// 动态主题样式生成器
export function generateThemeStyles(theme: 'light' | 'dark') {
  const baseStyles = {
    '--radius-sm': '0.375rem',
    '--radius-md': '0.5rem',
    '--radius-lg': '0.75rem',
    '--radius-xl': '1rem',
    '--transition-fast': '0.15s ease',
    '--transition-normal': '0.3s ease',
    '--transition-slow': '0.5s ease',
    '--shadow-sm': '0 1px 3px rgba(0, 0, 0, 0.1)',
    '--shadow-md': '0 4px 6px rgba(0, 0, 0, 0.1)',
    '--shadow-lg': '0 10px 15px rgba(0, 0, 0, 0.1)',
    '--shadow-xl': '0 20px 25px rgba(0, 0, 0, 0.1)'
  }

  const lightTheme = {
    '--primary-color': '#667eea',
    '--secondary-color': '#764ba2',
    '--text-primary': '#2d3748',
    '--text-secondary': '#718096',
    '--bg-primary': '#ffffff',
    '--bg-secondary': '#f7fafc',
    '--border-color': '#e2e8f0',
    '--accent-color': '#4299e1',
    '--success-color': '#48bb78',
    '--warning-color': '#ed8936',
    '--error-color': '#f56565'
  }

  const darkTheme = {
    '--primary-color': '#667eea',
    '--secondary-color': '#764ba2',
    '--text-primary': '#f7fafc',
    '--text-secondary': '#a0aec0',
    '--bg-primary': '#1a202c',
    '--bg-secondary': '#2d3748',
    '--border-color': '#4a5568',
    '--accent-color': '#63b3ed',
    '--success-color': '#68d391',
    '--warning-color': '#f6ad55',
    '--error-color': '#fc8181'
  }

  return {
    ...baseStyles,
    ...(theme === 'dark' ? darkTheme : lightTheme)
  }
}

// 主题切换动画
export function useThemeTransition() {
  const isTransitioning = ref(false)

  const startTransition = () => {
    isTransitioning.value = true
    document.documentElement.style.setProperty('--theme-transition-duration', '0.3s')

    setTimeout(() => {
      isTransitioning.value = false
    }, 300)
  }

  return {
    isTransitioning,
    startTransition
  }
}

// 主题感知组件
export function useThemeAwareComponent() {
  const { effectiveTheme } = useTheme()

  const componentClass = computed(() => {
    return effectiveTheme.value === 'dark' ? 'dark-mode' : 'light-mode'
  })

  const textColor = computed(() => {
    return effectiveTheme.value === 'dark' ? '#f7fafc' : '#2d3748'
  })

  const bgColor = computed(() => {
    return effectiveTheme.value === 'dark' ? '#1a202c' : '#ffffff'
  })

  return {
    componentClass,
    textColor,
    bgColor
  }
}

// 主题存储管理
export function useThemeStorage() {
  const THEME_STORAGE_KEY = 'app-theme'
  const THEME_TIMESTAMP_KEY = 'app-theme-timestamp'

  const saveTheme = (theme: Theme) => {
    try {
      localStorage.setItem(THEME_STORAGE_KEY, theme)
      localStorage.setItem(THEME_TIMESTAMP_KEY, Date.now().toString())
    } catch (error) {
      console.warn('Failed to save theme to localStorage:', error)
    }
  }

  const loadTheme = (): Theme | null => {
    try {
      const savedTheme = localStorage.getItem(THEME_STORAGE_KEY) as Theme
      const timestamp = localStorage.getItem(THEME_TIMESTAMP_KEY)

      if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
        // 检查主题是否过期（7天）
        if (timestamp) {
          const savedTime = parseInt(timestamp, 10)
          const currentTime = Date.now()
          const daysSinceSave = (currentTime - savedTime) / (1000 * 60 * 60 * 24)

          if (daysSinceSave > 7) {
            localStorage.removeItem(THEME_STORAGE_KEY)
            localStorage.removeItem(THEME_TIMESTAMP_KEY)
            return null
          }
        }
        return savedTheme
      }
    } catch (error) {
      console.warn('Failed to load theme from localStorage:', error)
    }
    return null
  }

  const clearTheme = () => {
    try {
      localStorage.removeItem(THEME_STORAGE_KEY)
      localStorage.removeItem(THEME_TIMESTAMP_KEY)
    } catch (error) {
      console.warn('Failed to clear theme from localStorage:', error)
    }
  }

  return {
    saveTheme,
    loadTheme,
    clearTheme
  }
}

// 主题工具函数
export const themeUtils = {
  // 获取对比色
  getContrastColor(hexcolor: string): string {
    const r = parseInt(hexcolor.substr(1, 2), 16)
    const g = parseInt(hexcolor.substr(3, 2), 16)
    const b = parseInt(hexcolor.substr(5, 2), 16)
    const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000
    return (yiq >= 128) ? '#000000' : '#ffffff'
  },

  // 颜色变亮
  lightenColor(hexcolor: string, amount: number): string {
    const num = parseInt(hexcolor.replace('#', ''), 16)
    const amt = Math.round(2.55 * amount)
    const R = (num >> 16) + amt
    const G = (num >> 8 & 0x00FF) + amt
    const B = (num & 0x0000FF) + amt
    return '#' + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
      (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
      (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1)
  },

  // 颜色变暗
  darkenColor(hexcolor: string, amount: number): string {
    return this.lightenColor(hexcolor, -amount)
  },

  // 生成渐变
  generateGradient(startColor: string, endColor: string, angle = 135): string {
    return `linear-gradient(${angle}deg, ${startColor} 0%, ${endColor} 100%)`
  }
}

// 主题配置
export const themeConfig = {
  themes: {
    light: {
      name: '浅色模式',
      icon: '☀️',
      description: '明亮的浅色主题'
    },
    dark: {
      name: '深色模式',
      icon: '🌙',
      description: '护眼的深色主题'
    },
    auto: {
      name: '自动模式',
      icon: '🔄',
      description: '跟随系统主题'
    }
  },

  // 主题切换快捷键
  shortcuts: {
    toggle: 'Ctrl+Shift+T',
    cycle: 'Ctrl+Alt+T'
  }
}

// 主题快捷键支持
export function useThemeShortcuts() {
  const { toggleTheme, setTheme } = useTheme()

  const handleKeydown = (event: KeyboardEvent) => {
    // Ctrl+Shift+T 切换主题
    if (event.ctrlKey && event.shiftKey && event.key === 'T') {
      event.preventDefault()
      toggleTheme()
    }

    // Ctrl+Alt+T 循环主题
    if (event.ctrlKey && event.altKey && event.key === 't') {
      event.preventDefault()
      toggleTheme()
    }

    // 数字键直接切换主题
    if (event.ctrlKey && event.altKey) {
      switch (event.key) {
        case '1':
          event.preventDefault()
          setTheme('light')
          break
        case '2':
          event.preventDefault()
          setTheme('dark')
          break
        case '3':
          event.preventDefault()
          setTheme('auto')
          break
      }
    }
  }

  const initShortcuts = () => {
    document.addEventListener('keydown', handleKeydown)
  }

  const removeShortcuts = () => {
    document.removeEventListener('keydown', handleKeydown)
  }

  return {
    initShortcuts,
    removeShortcuts
  }
}

// 主题初始化组合函数
export function useThemeInitializer() {
  const { initTheme } = useTheme()
  const { initShortcuts } = useThemeShortcuts()

  const initialize = () => {
    initTheme()
    initShortcuts()
  }

  return {
    initialize
  }
}

// 主题状态管理
export function useThemeState() {
  const themeState = ref({
    isLoaded: false,
    isTransitioning: false,
    currentTheme: 'auto' as Theme,
    effectiveTheme: 'light' as 'light' | 'dark',
    systemTheme: 'light' as 'light' | 'dark'
  })

  const updateThemeState = (updates: Partial<typeof themeState.value>) => {
    Object.assign(themeState.value, updates)
  }

  return {
    themeState,
    updateThemeState
  }
}

// 主题调试工具
export function useThemeDebugger() {
  const isDebugMode = ref(false)

  const toggleDebugMode = () => {
    isDebugMode.value = !isDebugMode.value
  }

  const logThemeInfo = () => {
    const { currentTheme, effectiveTheme, systemTheme } = useTheme()
    console.group('🎨 Theme Debug Info')
    console.log('Current Theme:', currentTheme.value)
    console.log('Effective Theme:', effectiveTheme.value)
    console.log('System Theme:', systemTheme.value)
    console.log('LocalStorage Theme:', localStorage.getItem('theme'))
    console.log('Document Classes:', document.documentElement.classList.value)
    console.groupEnd()
  }

  return {
    isDebugMode,
    toggleDebugMode,
    logThemeInfo
  }
}

// 主题性能优化
export function useThemePerformance() {
  const performanceMetrics = ref({
    themeSwitchTime: 0,
    styleRecalculationTime: 0,
    renderTime: 0
  })

  const measureThemeSwitch = async (switchFunction: () => Promise<void>) => {
    const startTime = performance.now()

    await switchFunction()

    const endTime = performance.now()
    performanceMetrics.value.themeSwitchTime = endTime - startTime

    console.log(`Theme switch took ${performanceMetrics.value.themeSwitchTime.toFixed(2)}ms`)
  }

  return {
    performanceMetrics,
    measureThemeSwitch
  }
}

// 主题辅助函数
export const themeHelpers = {
  // 检查是否支持暗色模式
  supportsDarkMode: () => {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches !== undefined
  },

  // 获取系统主题偏好
  getSystemThemePreference: (): 'light' | 'dark' => {
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      return 'dark'
    }
    return 'light'
  },

  // 检查主题是否有效
  isValidTheme: (theme: string): theme is Theme => {
    return ['light', 'dark', 'auto'].includes(theme)
  },

  // 主题切换动画
  animateThemeTransition: (duration = 300) => {
    document.documentElement.style.setProperty('--theme-transition-duration', `${duration}ms`)
    document.documentElement.classList.add('theme-transitioning')

    setTimeout(() => {
      document.documentElement.classList.remove('theme-transitioning')
    }, duration)
  }
}

// 主题Hook组合
export function useThemeHooks() {
  const theme = useTheme()
  const themeStorage = useThemeStorage()
  const themeShortcuts = useThemeShortcuts()
  const themePerformance = useThemePerformance()
  const themeDebugger = useThemeDebugger()

  return {
    ...theme,
    ...themeStorage,
    ...themeShortcuts,
    ...themePerformance,
    ...themeDebugger
  }
}

// 主题上下文提供器
export function provideThemeContext() {
  const theme = useTheme()
  const themeState = useThemeState()
  const themePerformance = useThemePerformance()

  return {
    theme,
    themeState,
    themePerformance
  }
}

// 主题Hook类型定义
export interface ThemeHook {
  currentTheme: Ref<Theme>
  effectiveTheme: ComputedRef<'light' | 'dark'>
  systemTheme: Ref<'light' | 'dark'>
  setTheme: (theme: Theme) => void
  toggleTheme: () => void
  initTheme: () => void
  themeIcon: ComputedRef<string>
  themeText: ComputedRef<string>
}

// 主题Hook工厂函数
export function createThemeHook(config: {
  defaultTheme?: Theme
  storageKey?: string
  enableShortcuts?: boolean
  enablePerformance?: boolean
} = {}): ThemeHook {
  const {
    defaultTheme = 'auto',
    storageKey = 'app-theme',
    enableShortcuts = true,
    enablePerformance = false
  } = config

  const theme = useTheme()
  const themeStorage = useThemeStorage()

  if (enableShortcuts) {
    const { initShortcuts } = useThemeShortcuts()
    initShortcuts()
  }

  if (enablePerformance) {
    useThemePerformance()
  }

  // 设置默认主题
  theme.currentTheme.value = defaultTheme

  return {
    ...theme,
    ...themeStorage
  }
}

// 默认导出
export default useTheme
export {
  useTheme,
  useThemeStorage,
  useThemeShortcuts,
  useThemePerformance,
  useThemeDebugger,
  useThemeInitializer,
  useThemeState,
  useThemeAwareComponent,
  useThemeTransition,
  useThemeHooks,
  provideThemeContext,
  createThemeHook,
  generateThemeStyles,
  themeUtils,
  themeHelpers,
  themeConfig
}

export type { Theme }